package com.iris.live.services.report.sources;


import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.data.repositories.ReportRepository;
import com.iris.live.services.report.Cell;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.report.Row;
import com.iris.live.services.report.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by lichao on 2017/4/11.
 */
@Component("ExportCluesSource")
public class ExportCluesSource  implements IExcelReportSource {
    private static final String [] titlesum = {"NO","线索姓名","电话号码","线索创建日期","来源渠道","意向级别","意向车型","销售顾问",
            "销售组","跟进日期","当天跟进通话时长","当天跟进备注","上一次跟进日期","上一次跟进通话时长","上一次跟进备注","最近一次进店日期","订单日期","开票日期"};
    private static final String [] titleone = {"NO","线索姓名","电话号码","线索创建日期","来源渠道","意向级别","意向车型","销售顾问",
            "销售组","当天跟进通话时长","当天跟进备注","上一次跟进日期","上一次跟进通话时长","上一次跟进备注","最近一次进店日期","订单日期","开票日期"};
    private static Logger logger = LoggerFactory.getLogger(ExportCluesSource.class);
    @Autowired
    private ReportRepository repository;

    @Override
    public Sheet[] getSheets(Map<String, Object> context) {
        String startTime = context.get("startTime").toString();
        String endTime = context.get("endTime").toString();
        List<String> timeList = new ArrayList<>();
        try {
            timeList = DateFormatUtils.splitDate(startTime,endTime);
        } catch (ParseException e) {
            logger.error("获取sheet个数出错");
        }
        Integer isPage = Integer.parseInt(context.get("isPage").toString());
        if(isPage==1) {
            Sheet[] sheets = new Sheet[timeList.size()];
            for(int i=0;i<timeList.size();i++) {
                sheets[i] = new Sheet("跟进线索清单报告--"+timeList.get(i), "跟进线索清单报告--"+timeList.get(i), true);
            }
            return sheets;
        }
        else{
            Sheet[] sheets = new Sheet[1];
            sheets[0] = new Sheet("跟进线索清单报告"+startTime+"--"+endTime, "跟进线索清单报告"+startTime+"--"+endTime, true);
            return sheets;
        }

    }

    @Override
    public List<Row> getSheetRows(Map<String, Object> context, Sheet sheet) {
        String [] titles=null;

        String dealer = (String) context.get("dealer");
        String startTime = context.get("startTime").toString();
        String endTime =  context.get("endTime").toString();
        Integer isPage = Integer.parseInt(context.get("isPage").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(isPage==1) {
            titles=titleone;
            try {
                Date start = DateFormatUtils.parseStrToSqlDate(startTime);
                Date end = DateFormatUtils.parseStrToSqlDate(endTime);
                if (start.getTime() > end.getTime()) {
                    return null;
                }
                startTime = end.toString();
                endTime = end.toString();
                context.put("endTime", DateFormatUtils.subStringToDate(endTime.toString(), 1));
            } catch (ParseException e) {
                return null;
            }
        }else{
            titles=titlesum;
        }

        int index;
        List<Row> rows = new ArrayList<>();
        Cell[] c = {new Cell(dealer, 5 ),new Cell(sdf.format(new java.util.Date()), 12 )};
        for(index = 0; index < 3; index++) {
            if(index == 1){
                rows.add(new Row(c));
            }else {
                rows.add(new Row());
            }
        }
        rows.add(new Row(getTitleCells(titles)));

        //数据输出
        index = 0;
        List<Map<String,Object>> list;
        List<Map<String,Object>> listLast;
        if(endTime.equals(sdf.format(new java.util.Date()))){//含当天时间
            //if(endTime.equals("2017-03-08")){//含当天时间
            list = repository.getCurrentCluesList(dealer,endTime);//当天数据
            if(startTime.equals(endTime)){  //只查当天数据

            }else{//查含有今天的区间范围
                listLast = repository.getCluesListDate(dealer,startTime,endTime);
                list.addAll(listLast);
            }
        }else {//不含当天时间
            list = repository.getCluesListDate(dealer, startTime, endTime);
        }
        if(list != null) {
                for (Object o : list) {
                    Map map = (Map) o;
                    String phone = (String) map.get("电话号码");
                    if (11 == phone.length()) {
                        phone = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
                        map.put("电话号码", phone);
                    }
                    rows.add(new Row(getDataCells(index++, titles, o)));
            }
        }

        return rows;
    }

    /**
     * 获取Excel 标题行
     * @param titles
     * @return
     */
    private  Cell[] getTitleCells(String[] titles){
        Cell[] cells = new Cell[titles.length];
        for(int index = 0; index < titles.length; index++){
            cells[index] = new Cell(titles[index], index );
        }

        return cells;
    }

    /**
     * 获取数据行
     * @param rowIndex
     * @param columns
     * @param o
     * @return
     */
    private Cell[] getDataCells(int rowIndex, String[] columns, Object o) {
        Map map = (Map) o;
        Cell[] cells = new Cell[columns.length];
        cells[0] = new Cell(rowIndex+1 + "", 0);
        for(int index = 1; index < columns.length; index++){
            String name = columns[index];
            cells[index] = new Cell(map.get(name) == null ? "" : map.get(columns[index]).toString(), index );
        }

        return cells;
    }
}